package cn.maihe.elg.operation.schedule;

import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.supports.bank.service.CiticBankCardService;
import cn.maihe.elg.operation.utils.ElgLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class CiticBankCardSchedule {

    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;

    @Resource
    private CiticBankCardService citicBankCardService;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void queryActiveCardTransactions() {
        ElgLogger.info(log, l -> l.info("开始定时任务：查询活跃状态的虚拟卡交易流水..."));

        // 从数据库中找出虚拟卡状态为 ACTIVE 的订单
        List<AcceptOrderInfoDO> activeCardOrders = acceptOrderInfoService.findOrdersWithActiveVirtualCards();

        if (activeCardOrders.isEmpty()) {
            ElgLogger.info(log, l -> l.info("当前无活跃状态的虚拟卡需要查询。"));
            return;
        }

        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 调用流水查询服务
        for (AcceptOrderInfoDO order : activeCardOrders) {
            try {
                citicBankCardService.queryAndSaveCardTransactions(
                        order.getVirtualCardNo(),
                        today,
                        today
                );
            } catch (Exception e) {
                ElgLogger.error(log, l -> l.error("查询订单 {} 的虚拟卡 {} 流水时出错", order.getAcceptOrderNo(), order.getVirtualCardNo(), e));
            }
        }
        ElgLogger.info(log, l -> l.info("虚拟卡交易流水定时查询任务执行完毕。"));
    }
}